#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
 
#include "data_type.h"
#include "cube.h"
#include "cube_define.h"
#include "cube_record.h"

#include "score_compute.h"
#include "flag_verify.h"

#include "score_write.h"
// add para lib_include

char Buf[DIGEST_SIZE*4];

static time_t max_time=2;

int score_write_init(void * sub_proc, void * para)
{
	int ret;

	return 0;
}

int score_write_start(void * sub_proc, void * para)
{
	int ret;
	void * recv_msg;
	int type;
	int subtype;
	// add yorself's module exec func here
	while(1)
	{
		usleep(time_val.tv_usec);

		ret=ex_module_recvmsg(sub_proc,&recv_msg);
		if(ret<0)
			continue;
		if(recv_msg==NULL)
			continue;
		type=message_get_type(recv_msg);
		subtype=message_get_subtype(recv_msg);
		if(!memdb_find_recordtype(type,subtype))
		{
			printf("message format (%d %d) is not registered!\n",
			message_get_type(recv_msg),message_get_subtype(recv_msg));
			continue;
		}
	   	if((type==TYPE(FLAG_VERIFY))&&(subtype==SUBTYPE(FLAG_VERIFY,SCORE)))
		{
			ret=proc_score_write(sub_proc,recv_msg);
		}
	}
	return 0;
}

int proc_score_write(void * sub_proc,void * recv_msg)
{
	int ret;
	int fd;
	RECORD(FLAG_VERIFY,FLAG) * flag_info;
	RECORD(FLAG_VERIFY,SCORE) * flag_score;
	RECORD(GENERAL_RETURN,STRING) * score_write;

	char file_name[DIGEST_SIZE*4];
	char score_buf[DIGEST_SIZE];


    	ret = message_get_record(recv_msg,&flag_score,0);
	if(ret<0)
		return -EINVAL;

	Strcpy(file_name,"/root/score_record/");
	Strcat(file_name,flag_score->name);
	Strcat(file_name,".txt");

	fd=open(file_name,O_WRONLY|O_CREAT|O_TRUNC);
	if(fd<0)
		return -EINVAL;
	Itoa(flag_score->score,score_buf);
	write(fd,score_buf,Strlen(score_buf));
	close(fd);
	ex_module_sendmsg(sub_proc,recv_msg);
	return 0;
}
